package bankTest;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

public class UserAccount {
	
	private ArrayList<User> users = new ArrayList<User>();
	
	public UserAccount() throws IOException {
		File file = new File("user.txt");
		if(file.exists()){
			FileReader fr = new FileReader(file);
			BufferedReader br = new BufferedReader(fr);
			String str;
			while((str = br.readLine())!= null){
				String[] nameAndPsd = str.split(":");
				User user = new User(nameAndPsd[0], nameAndPsd[1]);
				users.add(user);
			}
		}
	}
	
	public void login(User user) throws IOException{
		if(users.size()>0){
			if(users.contains(user)){
				checkMoney(user);
				System.out.println(user);
			}
		}
	}
	
	public void checkMoney(User user) throws IOException{
		FileReader save = new FileReader("save.txt");
		FileReader withDraw = new FileReader("withdraw.txt");
		
		BufferedReader savebr = new BufferedReader(save);
		BufferedReader wdbr = new BufferedReader(withDraw);
		
		String saveStr;
		int total = 0;
		while((saveStr = savebr.readLine())!= null){
			String[] cont = saveStr.split(":");
			if(cont[0].equals(user.getName())){
				total += Integer.parseInt(cont[1]);
			}
		}
		
		while((saveStr = wdbr.readLine())!= null){
			String[] cont = saveStr.split(":");
			if(cont[0].equals(user.getName())){
				total -= Integer.parseInt(cont[1]);
			}
		}
		
		user.setMoney(total);
		
		wdbr.close();
		savebr.close();
		save.close();
		withDraw.close();
	}
}
